package ru.electron.menu.activities;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.net.Uri;
import android.os.Bundle;
import android.preference.Preference;
import android.provider.BaseColumns;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import ru.electron.menu.R;
import ru.electron.menu.fragments.DishDetailsFragment;
import ru.electron.menu.fragments.OrderListFragment;
import ru.electron.menu.network.PostTask;
import ru.electron.menu.network.SuccessAction;
import ru.electron.menu.provider.MenuProvider;
import ru.electron.menu.utils.PreferencesUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import static ru.electron.menu.provider.MenuProvider.KEY_ORDERED;

public class OrderActivity extends FragmentActivity {

    private static final String SEND_PART = "/sendOrder";

    private JSONObject getOrderJson(Cursor c) {
        JSONObject result = new JSONObject();
        try {

            c.moveToPosition(-1);

            List<String> dishes = new ArrayList<String>();
            while (c.moveToNext()) {

                int countInd = c.getColumnIndex(MenuProvider.KEY_COUNT);
                int indexId = c.getColumnIndex(BaseColumns._ID);
                if (countInd == -1){
                    continue;
                }
                int count = c.getInt(countInd);
                String id = c.getString(indexId);
                for (int i = 0; i < count; i++) {
                    dishes.add(id);
                }
            }
            result.put("id", PreferencesUtil.getRequestId(this) + "");
            result.put("session-id", PreferencesUtil.getSessionId(this) + "");
            result.put("time", (System.currentTimeMillis() / 1000) + "");
            JSONArray dishArray = new JSONArray(dishes);
            result.put("ordered-dishes", dishArray);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return result;
    }

    private double countTotal(Cursor c) {
        if (c == null) {
            return 0;
        }


        double result = 0.;
        c.moveToPosition(-1);
        while (c.moveToNext()) {
            int priceInd = c.getColumnIndex(MenuProvider.KEY_PRICE);
            int id = c.getColumnIndex(MenuProvider.KEY_COUNT);
            if (id == -1) {
                id = c.getColumnIndex(KEY_ORDERED);
            }
            if (id == -1) {
                continue;
            }
            System.out.println(priceInd + " " + id);
            result += c.getDouble(priceInd) * c.getInt(id);
        }
        return result;
    }

    private static final int DIALOG_CLEAR = 1;
    private static final int DIALOG_SUCCESS = 2;
    private static final int DIALOG_FAIL = 3;

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_CLEAR:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setIcon(android.R.drawable.ic_dialog_alert);
                builder.setTitle(android.R.string.dialog_alert_title);
                builder.setMessage(R.string.clear_msg);
                builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        clear(MenuProvider.URI_ORDER);
                    }
                });

                builder.setNegativeButton(android.R.string.no, null);
                return builder.create();
            case DIALOG_SUCCESS:
                AlertDialog.Builder success = new AlertDialog.Builder(this);
                success.setIcon(android.R.drawable.ic_dialog_info);
                success.setMessage(R.string.success_msg);
                success.setTitle(R.string.thanks);
                success.setPositiveButton(android.R.string.ok, null);
                return success.create();
            case DIALOG_FAIL:
                AlertDialog.Builder fail = new AlertDialog.Builder(this);
                fail.setIcon(android.R.drawable.ic_dialog_alert);
                fail.setMessage(R.string.fail_msg);
                fail.setTitle(android.R.string.dialog_alert_title);

                fail.setPositiveButton(android.R.string.ok, null);
                return fail.create();
        }
        return super.onCreateDialog(id);
    }

    private void clear(Uri uri) {
        getContentResolver().delete(uri, null, null);
        DishDetailsFragment details = DishDetailsFragment.newInstance(-1, false);

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

        ft.replace(R.id.details_fragment, details);
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        ft.commit();

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.order_activity);

        final TextView total = (TextView) findViewById(R.id.total);
        OrderListFragment orderListFragment = (OrderListFragment) getSupportFragmentManager().findFragmentById(R.id.list_fragment);

        final Cursor cursor = orderListFragment.getCursor();
        total.setText("" + countTotal(cursor));
        cursor.registerDataSetObserver(new DataSetObserver() {
            @Override
            public void onChanged() {
                total.setText("" + countTotal(cursor));
            }
        });


        Button clearButton = (Button) findViewById(R.id.clear);
        clearButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialog(DIALOG_CLEAR);
            }
        });

        Button placeOrder = (Button) findViewById(R.id.order);
        placeOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PostTask postTask = new PostTask(SEND_PART);

                postTask.execute(getOrderJson(cursor));
                postTask.setSuccessAction(new SuccessAction() {
                    @Override
                    public void onSuccess(HttpResponse response) {
                        clear(MenuProvider.URI_SENT);
                        showDialog(DIALOG_SUCCESS);
                        try {
                            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                            JSONObject reqRes = new JSONObject(reader.readLine());
                            PreferencesUtil.setRequestId(OrderActivity.this, new Integer(reqRes.getString("id")));
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
                postTask.setOnFailureAction(new Runnable() {
                    @Override
                    public void run() {
                        showDialog(DIALOG_FAIL);
                    }
                });
            }
        });

    }
}
